#include<stdio.h>
#include<string.h>
#include<stdlib.h>

#define MAX_QUEUE_SIZE 10

typedef struct _array_queue
{
        int size;
        int num;
        int head;
        int tail;
        int *array;
}array_queue;

#define array_queue_is_empty(array_queue)       (array_queue->num == 0)
#define array_queue_is_full(array_queue)        ((array_queue->num) == (array_queue->size))


array_queue *array_queue_create(int size)
{
	array_queue *queue = NULL;
	queue = (array_queue *)malloc(sizeof(array_queue));
	if(queue == NULL)
		return NULL;

	queue->array = (int *)malloc(sizeof(int) * size);

	if(queue->array == NULL)
	{
		free(queue);
		return NULL;
	}
	queue->head = 0;
	queue->tail = 0;
	queue->size = size;
	queue->num = 0;

	return queue;
}


void array_queue_destory(array_queue *queue)
{
	if(queue == NULL)
		return;
	if(queue->array != NULL)
		free(queue->array);

	free(queue);

	return;
}

int array_queue_enqueue(array_queue *queue,int data)
{
	if(queue == NULL || array_queue_is_full(queue))
	{
		return -1;
	}
	queue->array[queue->tail] = data;
	queue->num++;
	queue->tail = (queue->tail + 1)%queue->size;

	return 0;
}

int array_queue_dequeue(array_queue *queue,int *data)
{
	if((queue == NULL) || (data == NULL) || (array_queue_is_empty(queue)))
	{
		return -1;
	}

	*data = queue->array[queue->head];
	queue->num--;

	queue->head = (queue->head + 1) %queue->size;

	return 0;
}

void array_queue_dump(array_queue *queue)
{
	int i = 0;
	int pos = 0;

	if((queue == NULL) || array_queue_is_empty(queue))
	{
		printf("queue is empty\n");
		return;
	}

	for(i = 0;i<queue->num;i++)
	{
		pos = (queue->head + i)%queue->size;
		printf("array[%d] = %d\n",pos,queue->array[pos]);
	}

	return;
}

int main()
{
	int i,ret,data;
	array_queue *queue = NULL;
	queue = array_queue_create(MAX_QUEUE_SIZE);
	if(queue == NULL)
	{
		printf("queue is create failed\n");
		return 0;
	}
	ret = array_queue_dequeue(queue,&data);
	if(ret !=0)
	{
		printf("queue dequeue failed=%d\n",ret);
	}

	for(i = 0;i<MAX_QUEUE_SIZE;i++)
	{
		ret = array_queue_enqueue(queue,i);
		if(ret != 0)
		{
			printf("queue enqueue failed=%d\n",ret);
		}
	}
	array_queue_dump(queue);

	ret = array_queue_dequeue(queue,&data);
	if(ret != 0)
		printf("array queue dequeue error=%d\n",ret);

	printf("dequeue data is=%d\n",data);

	array_queue_dump(queue);

	return 0;
}
